//
//  DDTUseAccountVC.swift
//  weibo
//
//  Created by mac on 16/9/28.
//  Copyright © 2016年 mac. All rights reserved.
//

import UIKit

class DDTUseAccountVC: NSObject {
    
    var useAccount: DDTUserAccount?

    static let shared: DDTUseAccountVC = DDTUseAccountVC()
    private override init() {
        super.init()
        useAccount = loadUserAccount()
    }
    
    
   
    
    func loadOauthAccessTokent(code: String, completion: (error: NSError?) -> Void) {
        
        let urlString = "https://api.weibo.com/oauth2/access_token"
        let parameters = [
            
            "client_id": client_id,
            "client_secret": client_secret,
            "grant_type": "authorization_code",
            "code": code,
            "redirect_uri": redirect_uri
        ]
        DDTNetworkTool.sharedInstance.request(DDTNetworkMethod.POST, URLString: urlString, parameters: parameters, progress: nil, sussess: { (_, responseObject) -> Void in
//            print("获取到了网络: \(responseObject)")
            let dict = responseObject as! [String: AnyObject]
            self.useAccount = DDTUserAccount(dict: dict)
           
            self.saveUserAccount()
            completion(error: nil)
            }) { (_, error:NSError) -> Void in
                print("获取网络失败")
               completion(error: error)
        }
    }
    
    let accountPath = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, .UserDomainMask, true).last!.stringByAppendingString("/userAccount.plist")
    
    //保存账户信息
    private func saveUserAccount() {
        if useAccount != nil {
            NSKeyedArchiver.archiveRootObject(useAccount!, toFile: accountPath)
            
        }
    }
    //从沙盒中加载用户信息
    private func loadUserAccount() -> DDTUserAccount? {
      let account =  NSKeyedUnarchiver.unarchiveObjectWithFile(accountPath) as? DDTUserAccount
        if account != nil && account?.expiresDate?.compare(NSDate()) == NSComparisonResult.OrderedDescending {
            return account

        }
        return nil
    }
    
    
    

}
